// append.c -- 把文件内容附加到另一个文件末尾

#include <stdio.h>
#include <stdlib.h>     // exit() 函数
#include <string.h>     // strcmp() 和 strchr() 函数

#define BUFSIZE 4096    // 缓冲区大小
#define SLEN 81         // 文件最大长度

void append(FILE *source, FILE *dest);
char *s_gets(char *st, int n);

int main(int argc, char const *argv[])
{
    FILE *fa, *fs;   // fa 指向目标文件，fs 指向源文件
    int files = 0;      // 添加的文件个数
    char file_app[SLEN];    // 目标文件名
    char file_src[SLEN];    // 源文件名
    int ch;

    puts("Enter name of destination file:");
    s_gets(file_app, SLEN);
    if ((fa = fopen(file_app, "a+")) == NULL) {
        fprintf(stderr, "Can't open %s.\n", file_app);
        exit(EXIT_FAILURE);
    }
    if (setvbuf(fa, NULL, _IOFBF, BUFSIZE) != 0) {
        fprintf(stderr, "Can't create output buffer.\n");
        exit(EXIT_FAILURE);
    }
    puts("Enter name of first source file (empty line to quit):");
    while (s_gets(file_src, SLEN) && file_src[0] != '\0') {
        if (strcmp(file_src, file_app) == 0) {
            fputs("Can't append file to itself.\n", stderr);
        }
        else if ((fs = fopen(file_src, "r")) == NULL) {
            fprintf(stderr, "Can't open %s.\n", file_src);
        }
        else {
            if (setvbuf(fs, NULL, _IOFBF, BUFSIZE) != 0) {
                fprintf(stderr, "Can't create input buffer.\n");
                continue;
            }
            append(fs, fa);
            if (ferror(fs) != 0) {
                fprintf(stderr, "Error in reading file %s.\n");
            }
            if (ferror(fa) != 0) {
                fprintf(stderr, "Error in writing file %s.\n");
            }
            fclose(fs);
            files++;
            printf("File %s appended.\n", file_src);
            puts("Next file (empty lien to quit):");
        }
    }
    printf("\nDone appending. %d files appended.\n", files);
    rewind(fa);
    printf("%s contents:\n", file_app);
    while ((ch=getc(fa)) != EOF) {
        putchar(ch);
    }
    puts("Done displaying.");
    fclose(fa);

    return 0;
}

void append(FILE *source, FILE *dest) {
    size_t bytes;
    static char temp[BUFSIZE];      // 只分配一次

    while ((bytes = fread(temp, sizeof(char), BUFSIZE, source)) > 0) {
        fwrite(temp, sizeof(char), bytes, dest);
    }
}

char * s_gets(char *st, int n) {
    char *ret_val;
    char *find;

    ret_val = fgets(st, n, stdin);
    if (ret_val) {
        find = strchr(st, '\n');    // 查找换行符
        if (find) {                 // 如果地址不是 NULL
            *find = '\0';           // 替换成空字符
        }
        else {
            while (getchar() != '\n') {
                continue;
            }
        }
    }

    return ret_val;
}


